package org.filedetail;

import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.db.Session;
import cn.hutool.db.ds.DSFactory;
import cn.hutool.db.ds.GlobalDSFactory;
import cn.hutool.setting.Setting;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class TxTest {

    @Test
    public void t1() throws IOException {
        String workDir = App.getWorkDir();
        String dbUrl = String.format("jdbc:sqlite:%s/file-detail-recorder.db", workDir);
        String name = new File(dbUrl).getName();
        System.out.println(dbUrl);
        System.out.println(name);
        String file = ResourceUtil.getResource("create.txt").getFile();
        String create = FileUtils.readFileToString(new File(file), "UTF-8");
        System.out.println(create);

        Path path = Paths.get("C:/Users/yangyang/Desktop/create.db");
        if (Files.exists(path)) {
            Files.write(path, new byte[0], StandardOpenOption.TRUNCATE_EXISTING);
        } else {
            Files.createFile(path);
        }

        testTx("jdbc:sqlite:C:/Users/yangyang/Desktop/create.db", create);
    }

    public void testTx(String dbUrl, String sql) {
        // 设置SQLite配置信息
        Setting setting = new Setting();
        setting.set("url", dbUrl); // 替换为你的数据库文件路径
        //setting.set("user", ""); // SQLite 通常不需要用户名
        //setting.set("password", ""); // SQLite 通常不需要密码
        setting.set("driverClassName", "org.sqlite.JDBC"); // SQLite的JDBC驱动类名

        // 创建SQLite配置对象
        DSFactory dsFactory = DSFactory.create(setting);
        GlobalDSFactory.set(dsFactory);

        //默认数据源
        Session session = Session.create();
        try {
            session.beginTransaction();//绑定
            int execute = session.execute(sql);
            System.out.println(execute);
            //
            session.commit();//提交事务
        } catch (Exception e) {
            session.quietRollback();//回滚
            e.printStackTrace();
        } finally {
            session.close();//关闭会话
        }
    }

}
